﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using NCrawler.Extensions;

namespace ZCrawler
{
    [Serializable()]
    public class ZBasicRule : ZRule
    {
        public string navMark { get; set; }
        public string startTag { get; set; }
        public string endTag { get; set; }
        public List<string> XPathes { get; set; }
        public string searchFieldTree { get; set; }
        public ZXPathType type { get; set; }
        public ZBasicRule(string f_name)
        {
            processors = new List<ZCrawlDataProcessor>();
            filters = new List<ZFilter>();
            EnableFilters = false;
            EOF = false;
            tag = 0;
            FieldName = f_name;
        }
        public ZBasicRule() 
        {
            processors = new List<ZCrawlDataProcessor>();
            filters = new List<ZFilter>();
            EnableFilters = false;
            EOF = false;
            tag = 0;
            FieldName = "";
        }
        public override void AddCrawlDataProcessor(ZCrawlDataProcessor processor)
        {
            processors.Add(processor);
        }

        public override string Process(HtmlAgilityPack.HtmlDocument doc)
        {
            return doc.DocumentNode.OuterHtml;
        }
        public override string Process<T>(T source)
        {
            return "";
        }
        public override void reset()
        {
            tag = 0;
            EOF = false;
        }
        public override string Description()
        {
            return "";
        }
        public string XPath
        {
            get
            {
                if (XPathes.IsNull()) return "";
                string r = "<XPathes>";
                XPathes.ForEach(x =>
                {
                    r += "<XPath>{0}</XPath>".FormatWith(x);
                });
                r += "</XPathes>";
                return r;
            }
        }
        public bool Validate()
        {
            return !(XPathes.IsNull() && startTag.IsNullOrEmpty() && endTag.IsNullOrEmpty() && navMark.IsNullOrEmpty() && searchFieldTree.IsNullOrEmpty());
        }
        public void SetReachEndTag(bool eof)
        {
            EOF = eof;
        }
        public bool IsEnd
        {
            get
            {
                return EOF;
            }
        }
        public bool IsAnyFilterMatched(ZResult r)
        {
            if (r[FieldName].IsNull() || !EnableFilters) return false;

            bool result = false;
            string val = r[FieldName].ToString();
            foreach(ZFilter filter in filters)
            {
                if (filter.WillFilter<string>(val))
                {
                    result = true;
                    break;
                }
            }
            return result;
        }
    }
}
